package com.fms.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.fms.entity.Orders;
import com.fms.exception.ServiceException;
import com.fms.properties.AliOSSProperties;
import com.fms.result.ResultData;
import com.fms.service.OrdersService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrdersController {
    private final AliOSSProperties aliOSSProperties;

    private final OrdersService ordersService;

    //新增或更新订单
    @PostMapping("/addOrSaveOrder")
    public ResultData addOrSaveOrder(@RequestBody Orders orders){
        ResultData resultData = ordersService.addOrSaveOrder(orders);
        return resultData;
    }

    //获取所有订单
    @GetMapping("/getOrders")
    public ResultData getOrders(){
        List<Orders> list = ordersService.getOrders();
        return ResultData.success(list);
    }

    //获取指定订单
    @GetMapping("/getOrder/{id}")
    public ResultData getOrders(@PathVariable("id") Long id){
        Orders order = ordersService.getOrder(id);
        return ResultData.success(order);
    }

    //删除订单
    @PostMapping("/deleteOrder/{id}")
    public ResultData deleteOrder(@PathVariable("id") String id){
        System.out.println(id);
        ResultData resultData = ordersService.deleteOrder(id);
        return resultData;
    }

    //流转订单
    @PostMapping("/transferOrder")
    public ResultData transferOrder(@RequestBody Orders orders){
        ResultData resultData = ordersService.transferOrder(orders);
        return resultData;
    }

    //更新订单材料
    @PostMapping("/updateOrderMaterial")
    //@PreAuthorize("hasAnyRole('设计师','管理员')")
    public ResultData updateOrderMaterial(@RequestBody Orders orders){
        ResultData resultData = ordersService.updateOrderMaterial(orders);
        return resultData;
    }

    //更新订单材料
    @PostMapping("/updatePayment")
    public ResultData updatePayment(@RequestBody Orders orders){
        ResultData resultData = ordersService.updatePayment(orders);
        return resultData;
    }

    //否决订单
    @PostMapping("/denyOrder")
    //@PreAuthorize("hasAnyRole('经理','总经理','管理员')")
    public ResultData denyOrder(@RequestBody Orders orders){
        ResultData resultData = ordersService.denyOrder(orders);
        return  resultData;
    }

    //通过订单
    @PostMapping("/passOrder")
    //@PreAuthorize("hasAnyRole('经理','总经理','管理员')")
    public ResultData passOrder(@RequestBody Orders orders){
        ResultData resultData = ordersService.passOrder(orders);
        return resultData;
    }

    //安装单
    //@PreAuthorize("hasAnyRole('安装师','管理员')")
    @PostMapping("/equipmentConfirm")
    public ResultData equipmentConfirm(@RequestBody Orders orders){
        System.out.println(orders.getInstallNote());
        ResultData resultData = ordersService.equipmentConfirm(orders);
        return resultData;
    }

    //出货单
    @PostMapping("/shipmentConfirm")
    public ResultData shipmentConfirm(@RequestBody Orders orders){
        ordersService.shipmentConfirm(orders);
        return ResultData.success("完成");
    }

    //更新财务尾款单
    @PostMapping("/updateFinalPayment")
    public ResultData updateFinalPayment(@RequestBody Orders orders){
        System.out.println(orders);
        ResultData resultData = ordersService.updateFinalPayment(orders);
        return resultData;
    }

    //更新订单材料附件
    @PostMapping("/uploadMaterial")
    public ResultData uploadImage(MultipartFile file) {
        if(file==null ){
            throw new ServiceException("请选择提交的文件");
        }
        try {
            return ResultData.success("success", uploadMaterialFile(file));
        } catch (IOException e) {
            throw new ServiceException("图片上传服务器失败");
        }
    }

    public String uploadMaterialFile(MultipartFile file) throws IOException {
        //用@ConfigurationProperties(prefix = " ")获取配置文件信息,获取阿里云OSS参数
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String bucketName = aliOSSProperties.getBucketName();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String endpoint = aliOSSProperties.getEndpoint();

        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = originalFilename;
        if (originalFilename != null) {
            fileName = originalFilename.substring(0,originalFilename.lastIndexOf(".")) + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }
}
